<template>
    <div class="login-container">
        <el-row>
            <el-col :span="9" :offset="7" class="login-box">
                <h1 class="title">欢迎登录</h1>
                <el-form :model="loginForm" :rules="loginFormRules" ref="loginFormRef">
                    <label for="用户名">
                        <el-form-item label="用户名" prop="username">
                            <el-input id="用户名" v-model="loginForm.username"></el-input>
                        </el-form-item>
                    </label>
                    <label for="密码">
                        <el-form-item label="密码" prop="password">
                            <el-input id="密码" v-model="loginForm.password" type="password"></el-input>
                        </el-form-item>
                    </label>
                    <el-form-item>
                        <el-button type="primary" @click="login('loginFormRef')"><span class="login_text">登录</span>
                        </el-button>
                        <el-button @click="resetLoginForm('loginFormRef')">重置</el-button>
                    </el-form-item>
                </el-form>
            </el-col>
        </el-row>
    </div>
</template>

<script>
  export default {
    name: "Login",
    data() {
      return {
        loginForm: {
          username:'admin',
          password:'123456'
          // username: '',
          // password: ''
        },
        loginFormRules: {
          username: [
            {required: true, message: '请输入用户名', trigger: 'blur'},
            {min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur'}
          ],
          password: [
            {required: true, message: '请输入密码', trigger: 'blur'},
            {min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur'}
          ]
        },
      }
    },
    methods: {
      resetLoginForm(formName) {
        this.$refs[formName].resetFields();
      },
      login(formName) {
        this.$refs[formName].validate(async (valid) => {
          if (!valid) return this.$message.error('表单不合法');
          const {data: res} = await this.$http({
            url: 'login',
            method: 'post',
            data: this.loginForm
          });
          if (res.meta.status === 403) return this.$message.error(res.meta.msg);
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
          window.sessionStorage.setItem('token', res.data.token);
          this.$router.push('/home');
          return this.$message.success('登录成功');
        });
      }
    }
  }
</script>

<style scoped>
    .login-container {
        text-align: right;
        margin-top: 100px;

    }

    .login-box {
        padding: 5px 50px;
        box-shadow: 0 0 20px #909399;
    }

    .title {
        text-align: center;
    }

    .login_text {
        color: #303133;
    }
</style>